package com.billjc.activity.util;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


public class TransXmlUtil {
	public <T> String marshal(T t) {
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[] { t.getClass() });

			Marshaller marshaller = jc.createMarshaller();

			StringWriter writer = new StringWriter();

			marshaller.setProperty("jaxb.encoding", DataUtil.encoding);

			marshaller.setProperty("jaxb.formatted.output", Boolean.valueOf(DataUtil.isFormatter));

			marshaller.setProperty("jaxb.fragment", Boolean.valueOf(DataUtil.isIgnore()));

			marshaller.marshal(t, writer);

			return writer.toString();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}

	public <T> T unmarshal(String xmlString, T t) {
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[] { t.getClass() });

			Unmarshaller unmarshaller = jc.createUnmarshaller();

			StringReader reader = new StringReader(xmlString);

			t = (T) unmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return t;
	}

	public <T> T unmarshal(File file, T t) {
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[] { t.getClass() });

			Unmarshaller unmarshaller = jc.createUnmarshaller();

			t = (T) unmarshaller.unmarshal(file);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return t;
	}

	public static void main(String[] args) {
	}
}
